﻿using System.Data.Entity.Migrations;
using System.Linq;
using RBOSS.Data;
using RBOSS.Utilities;

namespace RBOSS.Business.LoginModule
{
    public class LoginSubSystem : ILoginSubSystem
    {
        private readonly RBOSSEntities _entities;
        private readonly RandomPasswordGenerator _randomPasswordGenerator;

        public LoginSubSystem()
        {
            _entities = new RBOSSEntities();
            _randomPasswordGenerator = new RandomPasswordGenerator();
        }

        public string GetName(string email)
        {
            var name = (from n in _entities.Users where n.Email == email select n.FirstName).FirstOrDefault();
            return name;
        }

        public bool ValidateLogin(string userEmail, string password)
        {
            var emailExists = _entities.Users.FirstOrDefault(x=>x.Email == userEmail);
            if (emailExists == null)
                return false;
            if (emailExists.Password == password)
                return true;
            return false;
        }

        public string GetRole(string userEmail)
        {
            return _entities.Users.First(x => x.Email == userEmail).Role.RoleName;
        }

        public bool ForgetPassword(string userEmail)
        {
            var exists = _entities.Users.FirstOrDefault(x => x.Email == userEmail);
            if (exists == null)
                return false;
            var randomPassword = _randomPasswordGenerator.Generate(10);
            exists.Password = RBOSSecurity.Encrypt(randomPassword);
            _entities.Users.AddOrUpdate(exists);
            _entities.SaveChanges();
            return true;
        }

        public bool CheckEmailAddress(string emailAddress)
        {
            var exists = _entities.Users.FirstOrDefault(x => x.Email == emailAddress);
            return exists != null;
        }

        public void UpdatePassword(string emailAddress, string encryptedPassword)
        {
            var exists = _entities.Users.FirstOrDefault(x => x.Email == emailAddress);
            
            exists.Password = encryptedPassword;
            _entities.Users.AddOrUpdate(exists);
            _entities.SaveChanges();
        }
    }
}